/**
 *   Kaltura Browser - components/com_kaltura/assets/js/kaltura.js
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Author: Miguel Puig Garcia (miguel@bittingbits.com)
 *   Copyright (C) 2011 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
window.addEvent('domready', function() {
    // loading modalbox
    SqueezeBox.initialize({});
    // adding it as a prototype object enables it to be used from any array
    Array.prototype.removeItems = function(itemsToRemove) {

        if (!/Array/.test(itemsToRemove.constructor)) {
            itemsToRemove = [ itemsToRemove ];
        }

        var j;
        for (var i = 0; i < itemsToRemove.length; i++) {
            j = 0;
            while (j < this.length) {
                if (this[j] == itemsToRemove[i]) {
                    this.splice(j, 1);
                } else {
                    j++;
                }
            }
        }
    }
    
    function recalcPaginator() {
        // recalc paginator classes
        if (page == 1) {
            $('first').removeClass('enabled');
            $('prev').removeClass('enabled');
        } 
        if (page == $('tpages').getProperty('value')) {
            $('last').removeClass('enabled');
            $('next').removeClass('enabled');
        }
        if (page > 1) {
            $('first').addClass('enabled');
            $('prev').addClass('enabled');
        }
        if (page < $('tpages').getProperty('value')) {
            $('next').addClass('enabled');
            $('last').addClass('enabled');
        }
    }
    
    // box behavior
    var slide1 = new Fx.Slide('boxtab1-content');
    var slide2 = new Fx.Slide('boxtab2-content');
    var page = 1;
    
    var mediafilters = new Array();
    var transcodingfilters = new Array();
    var durationfilters = new Array();
    var statusesfilters = new Array();
    var flavorsfilters = new Array();
    
    var startdate = "";
    var enddate = "";
    
    var selectedCategory = "categoriesall";
    
    slide1.slideIn();
    slide2.slideOut();
    
    function loadTable() {
        var url = 'index.php?option=com_kaltura&controller=browser&task=loadTable&format=raw';
        $('loadingbox').removeClass('notvisible');
        
        new Ajax(url, {
            method: 'post',
            data: {
                'page': page,
                'tableid': $('tableid').getProperty('value'),
                'q': $('searchfield').getProperty('value'),
                'mediafilters': mediafilters,
                'durationfilters': durationfilters,
                'startdate': startdate,
                'enddate': enddate,
                'cat': selectedCategory
            },
            onComplete: function(data) {
                $('table_tbody').setHTML(data);
                $$('.clickrow').addEvent('click', function() {
	                var url = 'index.php?option=com_kaltura&controller=details&task=showDetails&tmpl=component';
	                var id_full = this.getProperty('id');
	                var id = id_full.substring(3);

	                new Ajax(url, {
	                    method: 'post',
	                    data: {
	                        'tableid': $('tableid').getProperty('value'),
	                        'itemid': id
	                    },
	                    onComplete: function(data) {
	                        $('sqbox').setHTML(data);
	                        var launcher = new Element('a', {'href':'#sqbox'});
	                        SqueezeBox.fromElement(launcher, { 
	                            handler: 'adopt', 
	                            adopt: 'sqbox',
	                            size: {x: 880, y: 380}
	                        });
	                    }
	                }).request();
            });
            
            $('actualpage').setHTML($('rpage').getProperty('value'));
            page = $('rpage').getProperty('value');
            $('totalpages').setHTML($('rtpage').getProperty('value'));
            $('page').setProperty('value', page);
            $('tpages').setProperty('value', $('rtpage').getProperty('value'));
            $('loadingbox').addClass('notvisible');
            recalcPaginator();
            }
        }).request();
    }
    
    loadTable();
    
    document.body.onkeypress = function() {
        event = event || window.event;
        if (event.keyCode == 13) {   
            loadTable();
            return false;
        }
        return true;
    }
    
    $('first').addEvent('click', function() {
        page = 1;
        $('actualpage').setHTML('1');
        $('page').setProperty('value', 1);
        loadTable();
    });
    
    $('last').addEvent('click', function() {
        page = $('tpages').getProperty('value');
        $('actualpage').setHTML(page);
        $('page').setProperty('value', page);
        loadTable();
    });
    
    $('prev').addEvent('click', function() {
        if (page > 1) {
            page--;
            $('actualpage').setHTML(page);
            $('page').setProperty('value', page);
        }
        loadTable();
    });
    
    $('next').addEvent('click', function() {
        if (page < $('tpages').getProperty('value')) {
            page++;
            $('actualpage').setHTML(page);
            $('page').setProperty('value', page);
        }
        loadTable();
    });
    
    $('searchstart').addEvent('click', function() {
        // it should change actual page to 1
        loadTable();
    });
    
    $$('#boxtab1 .boxtab-header').addEvent('click', function() {
        slide1.slideIn();
        slide2.slideOut();
    });
    
    $$('#boxtab2 .boxtab-header').addEvent('click', function() {
        slide2.slideIn();
        slide1.slideOut();
    });
        
    function toggle() {
        var classtext = this.getProperty('class');
        if (classtext.indexOf('selected') != -1) {
            this.removeClass('selected');
        } else this.addClass('selected');
        this.addEvent('click', toggle);
    }
    
    $$('#filtersarea ul li').addEvent('click', toggle);
    
    $$('.duration').addEvent('click', function() {
        var id = this.getProperty('id');
        
        if (this.hasClass('selected')) {
            if (id == 'durationshort') durationfilters.push(1);
            if (id == 'durationmedium') durationfilters.push(2);
            if (id == 'durationlong') durationfilters.push(3);
        } else {
            if (id == 'durationshort') durationfilters.removeItems([1]);
            if (id == 'durationmedium') durationfilters.removeItems([2]);
            if (id == 'durationlong') durationfilters.removeItems([3]);
        }
    
        var objs = $$('.duration');
        var has = false;
        for (var i=0; i < 3; i++) {
            var elem = objs[i];
            if (elem instanceof HTMLLIElement)
                if (elem.getProperty('class').indexOf('selected') != -1) {
                    has = true;
                }
        }
        if (has) $('durationall').removeClass('selected');
        else $('durationall').addClass('selected');
        loadTable();
    });
    
    $$('.mediatype').addEvent('click', function() {
        var id = this.getProperty('id');
        
        if (this.hasClass('selected')) {
            if (id == 'video') mediafilters.push(1);
            if (id == 'audio') mediafilters.push(5);
        } else {
            if (id == 'video') mediafilters.removeItems([1]);
            if (id == 'audio') mediafilters.removeItems([5]);
        }
    
        var objs = $$('.mediatype');
        var has = false;
        for (var i=0; i < 3; i++) {
            var elem = objs[i];
            if (elem instanceof HTMLLIElement)
                if (elem.getProperty('class').indexOf('selected') != -1) {
                    has = true;
                }
        }
        if (has) $('mediatypeall').removeClass('selected');
        else $('mediatypeall').addClass('selected');
        loadTable();
    });
    
    $$('.category').addEvent('click', function() {
        selectedCategory = this.getProperty('id');
        
        if ($('parent'+selectedCategory)) {
            var boxes = $$('.childrenbox');
            for (var i in boxes) {
                var box = boxes[i];
                if (box instanceof HTMLDivElement) {
                    var boxSlide = new Fx.Slide(box.getProperty('id'));
                    boxSlide.slideOut();
                }
            }
            var parentSlide = new Fx.Slide('children'+selectedCategory)
            parentSlide.slideIn();
        }
        $$('.category').removeClass('selected');
        this.addClass('selected');
        
        loadTable();
    });
});
